import FirstTitle from "@/components/FirstTitle";
import SubTitle from "@/components/subTitle";
import EffectContainer from "@/components/effectContainer";

import {
  useCallback,
  useEffect,
  useLayoutEffect,
  useRef,
  useState,
} from "react";
import "./index.scss";
import axios from "axios";
import Code from "@/components/code";

const CardHover = () => {
  const gContainer: any = useRef(null);
  const gImg: any = useRef(null);
  const [code, setCode] = useState("");
  const [css, setCss] = useState("");

  useEffect(() => {
    axios.get(`${window.origin}/code/cardHover/代码.txt`).then(({ data }) => {
      setCode(data);
    });
    axios
      .get(`${window.origin}/code/cardHover/css代码.txt`)
      .then(({ data }) => {
        setCss(data);
      });
  }, []);
  const handlerMove = useCallback((event) => {
    gImg.current.style.visibility = "visible";

    const target = event.target;
    const rect = target.getBoundingClientRect();

    const offsetX = event.clientX - rect.left;
    const offsetY = event.clientY - rect.top;

    const percentX = (
      Math.min(Math.max(offsetX / rect.width, 0), 1) * 100
    ).toFixed(2);
    const percentY = (
      Math.min(Math.max(offsetY / rect.height, 0), 1) * 100
    ).toFixed(2);

    gContainer.current.setAttribute(
      "style",
      `--x: ${percentX}%;--y: ${percentY}%;`,
    );
  }, []);

  const handlerMouseOut = useCallback(() => {
    gImg.current.style.visibility = "hidden";
  }, []);

  useLayoutEffect(() => {
    gContainer.current.addEventListener("mousemove", handlerMove);
    gContainer.current.addEventListener("mouseout", handlerMouseOut);
    return () => {
      gContainer.current.removeEventListener("mousemove", handlerMove);
    };
  }, []);
  return (
    <>
      <FirstTitle title="卡片Hover" />
      <SubTitle title="效果" />
      <EffectContainer
        effect={
          <div id="g-container" ref={gContainer}>
            <div id="g-filter"></div>
            <div id="g-img" ref={gImg}></div>
          </div>
        }
        code={<Code content={code} />}
        css={<Code content={css} type="css" />}
      ></EffectContainer>
    </>
  );
};
export default CardHover;
